package org.jeecg.modules.demo.crm.util.wx;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.jeecg.modules.demo.crm.entity.CWeixin;
import org.jeecg.modules.demo.crm.mapper.CWeixinMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class WxService {

    @Autowired
    private WxConfig wxConfig;
    @Autowired
    private CWeixinMapper cWeixinMapper;

    public JSONObject getOpenIdByCode(String code) {
        String url = String.format(
                "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code",
                wxConfig.getAppId(), wxConfig.getSecret(), code
        );
        String result = HttpUtil.get(url);
        System.out.println("获取openId"+result);
        if(result != null ){
            JSONObject jsonObject = JSON.parseObject(result);
            if(jsonObject.getString("openid") != null){
                CWeixin wxeixin = cWeixinMapper.findByOpenId(result);
                if(wxeixin == null){
                    return getUserInfo(jsonObject.getString("access_token"), jsonObject.getString("openid"), jsonObject);
                }else {
                    String dataInfo = wxeixin.getDataInfo();
                    JSONObject dataInfoJson = JSON.parseObject(dataInfo);
                    return dataInfoJson;
                }
            }

        }
        return new JSONObject();



        //return getUserInfo(getStableToken(), "oMw6fvsJnq5cNd8Z_YH6_4Bnp590", new JSONObject());
    }
    public JSONObject getUserInfo( String accessToken,String openId,JSONObject jsonObject) {
        try {
            String url = String.format("https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=LANG",accessToken, openId);
            String result = HttpUtil.get(url);
            System.out.println("获取用户信息"+result);
            JSONObject jsonObject1 = JSON.parseObject(result);
            if(jsonObject1.get("openid") != null) {
                return jsonObject1;
            }
        } catch (Exception e) {
            System.out.println("授权失败，只保存openId"+openId);
        }
        return jsonObject;
    }
    public String getStableToken() {
        JSONObject params = new JSONObject();
        params.put("grant_type", "client_credential");
        params.put("appid", wxConfig.getAppId());
        params.put("secret", wxConfig.getSecret());
        params.put("force_refresh",false);
        String result = HttpUtil.post("https://api.weixin.qq.com/cgi-bin/stable_token",JSON.toJSONString(params));
        System.out.println("获取token"+result);
        JSONObject jsonObject = JSON.parseObject(result);
        System.out.println(jsonObject);
        return jsonObject.getString("access_token");

    }

}
